package com.atguigu.spzx.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.model.dto.h5.UserLoginDto;
import com.atguigu.spzx.model.dto.h5.UserRegisterDto;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.UserInfoVo;
import com.atguigu.spzx.common.constant.CacheConstant;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //1.验证表单参数是否为空
        String username = userRegisterDto.getUsername(); //手机号
        String password = userRegisterDto.getPassword(); //密码 文明
        String nickName = userRegisterDto.getNickName(); //昵称
        String code = userRegisterDto.getCode(); //验证码

        if(!StringUtils.hasText(username) || !StringUtils.hasText(password) || !StringUtils.hasText(nickName) || !StringUtils.hasText(code)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //2.校验验证码是否正确
        String fromRedisCode = redisTemplate.opsForValue().get(CacheConstant.PHONE_VALIDATE_CODE_PREFIX + username);
        if(!code.equals(fromRedisCode)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //3.校验用户名是否存在
        UserInfo userInfo = userInfoMapper.getByUsername(username);
        if(userInfo!=null){ //用户名称已经被占用
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //4.保存用户信息
        userInfo = new UserInfo();
        userInfo.setUsername(username);  // 用户名称：可能是手机号或邮箱
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setNickName(nickName);
        userInfo.setPhone(null);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfo.setStatus(1);
        userInfoMapper.insert(userInfo);

        //5.删除缓存的验证码
        redisTemplate.delete(CacheConstant.PHONE_VALIDATE_CODE_PREFIX + username);
    }


    @Override
    public String login(UserLoginDto loginDto,String ip) {
        //1.校验登录参数是否为空
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        if(!StringUtils.hasText(username) || !StringUtils.hasText(password)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //2.校验用户名称，是否是已注册合法用户
        UserInfo userInfo = userInfoMapper.getByUsername(username);
        if(userInfo==null){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //3.校验密码是否正确
        if(!userInfo.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //4.判断账号是否被禁用
        if(userInfo.getStatus() == 0){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }

        //5.记录最后一次登录ip和时间，更新数据
        userInfo.setLastLoginIp(ip);
        userInfo.setLastLoginTime(new Date());
        userInfoMapper.updateById(userInfo);

        //6.生成token令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        userInfo.setPassword("");
        redisTemplate.opsForValue().set(CacheConstant.LOGIN_USERINFO_PREFIX+token, JSON.toJSONString(userInfo),30, TimeUnit.DAYS);
        return token;
    }


//    @Override
//    public UserInfoVo getCurrentUserInfo(String token) {
//        String userInfoJsonStr = redisTemplate.opsForValue().get(CacheConstant.LOGIN_USERINFO_PREFIX+token);
//
//        if(StringUtils.isEmpty(userInfoJsonStr)) {
//            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH) ;
//        }
//
//        UserInfo userInfo = JSON.parseObject(userInfoJsonStr, UserInfo.class);
//
//        UserInfoVo userInfoVo = new UserInfoVo();
//        BeanUtils.copyProperties(userInfo,userInfoVo); //属性拷贝，不需要一个一个复制了
////        userInfoVo.setNickName(userInfo.getNickName());
////        userInfoVo.setAvatar(userInfo.getAvatar());
//        return userInfoVo;
//    }
}
